package com.gopay.scheduler.job;

import java.math.BigDecimal;
import java.util.*;

import com.gopay.common.cipher.utils.SensitiveInfoUtils;
import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.cps.dao.acct.CommonQueryDAO;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.scheduler.service.cacert.CustCaCertService;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;

public class FreeCertInstallNotifyJob extends GopayBaseJob{

    private Logger logger = LoggerFactory.getLogger(getClass());

    private @Value("#{webProperties['portal.url']}")
    String portalUrl;

    @Resource(name = "custCaCertServiceCron")
    private CustCaCertService certService;

    @Resource(name = "comQueryDao")
    private CommonQueryDAO commonQueryDAO;

    @Override
    protected void doJobInternal() {
        logger.info("开始执行通知企业用户安装免费数字证书任务");

        List<Object[]> result = findByNotifySql();

        if(result == null || result.size() == 0){
            logger.info("通知企业用户安装免费数字证书结果集为空，结束任务。");
            return ;
        }
        logger.info("待通知的记录数 = " + result.size());

        //2.处理结果集
        for(Object[] raw : result){
            try {
                Date expireTs = (Date)raw[5];
                Date createTs = (Date)raw[5];
                BigDecimal freeCount = (BigDecimal)raw[6];

                if(StringUtils.isNotEmpty((String)raw[3])) {
                    // 企业邮箱不为空，发送邮件提醒
                    logger.error("email: " + (String)raw[3] +",custId: "+ (String)raw[1]);
                    sendMail(createTs,(String)raw[2], (String)raw[3], expireTs,freeCount);
                } else if(StringUtils.isNotEmpty((String)raw[4])){
                    String mobile = SensitiveInfoUtils.smartDecryptWithCheck((String)raw[4]);
                    logger.error("mobile: " +mobile  +",custId: "+(String)raw[1]);
                    sendSms((String)raw[2],mobile ,(Date)raw[5]);
                }else{
                    logger.error("通知企业用户安装免费数字证书失败，邮箱和手机号均为空,custId=",(String)raw[1]);
                }
            }catch (Exception e){
                logger.error("通知企业用户安装免费数字证书失败");
            }
        }
        logger.info("通知企业用户安装免费数字证书任务成功");
    }

    private List<Object[]> findByNotifySql(){
        Date date=new Date();
        String dateFormat="yyyy-MM-dd";
        String currentDate=DateUtils.format(date,dateFormat);

        Calendar c= Calendar.getInstance();
        //把日期往后减3天
        c.add(Calendar.DATE,-3);
        date=c.getTime();
        String threeDate = DateUtils.format(date,dateFormat);

        Calendar calendar = new GregorianCalendar();
        //把日期往后减6天
        calendar.add(Calendar.DATE,-6);
        date=calendar.getTime();
        String sixDate = DateUtils.format(date,dateFormat);

        Map<String,Object> param = new HashMap<String,Object>();
        param.put("currentDate", currentDate);
        param.put("threeDate", threeDate);
        param.put("sixDate", sixDate);

        StringBuilder sql = new StringBuilder();
        sql.append("select d.create_ts, d.cust_id,i.corp_name,i.email,i.cust_mob,d.install_expire_ts,d.count ");
        sql.append("from cust_ca_buy_dtl d left join cust_corp_info i on d.cust_id = i.cust_id ");
        sql.append(" where 1=1  and i.ca_cert_switch = '01' ");
        sql.append(" and d.dtl_type = '01'");
        sql.append(" and d.unused_count > 0 ");
        sql.append(" and d.drawback_ca_count = 0 ");
        sql.append(" and (d.audit_stat is null or d.audit_stat = '02') ");
        sql.append(" and to_char(d.install_expire_ts,'YYYY-MM-DD') > :currentDate  ");
        sql.append(" and (to_char(d.create_ts,'YYYY-MM-DD') = :threeDate or to_char(d.create_ts,'YYYY-MM-DD') = :sixDate ) ");

        logger.info("企业免费证书未过安装期限查询语句为：" + sql);
        return commonQueryDAO.findBySql(sql.toString(), param);

    }

    private void sendMail(Date createdTs,String custName,String Email,Date expireTs,BigDecimal freeCount) throws GopayException {
        String email = Email.trim().toLowerCase();
        String dateFormat = "yyyy-MM-dd";
        String expireDate = DateUtils.format(expireTs,dateFormat);
        String openDate = DateUtils.format(createdTs,dateFormat);
        Send send = new Send();
        send.setReceivers(email);
        send.setTemplate("corpCertInstallRemind");
        send.setLevel(MailLevel.MID);
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("custName", custName);
        json.put("replacethistotheLogoAddr", portalUrl);
        json.put("limitDate", expireDate);
        json.put("openDate", openDate);
        json.put("freeCount", freeCount);
        send.setContent(JSONObject.fromObject(json).toString());
        certService.sendMail(send);
    }

    /**
     * 发送短信
     * @param custName
     * @param mobile
     * @param expireTs
     * @throws GopayException
     */
    private void sendSms(String custName,String mobile, Date expireTs) throws GopayException {

        String dateFormat = "yyyy-MM-dd";
        String date = DateUtils.format(expireTs,dateFormat);
        RequestVO req = new RequestVO();
        req.setAppId(SMSAppId._90001.value);
        req.setMobile(mobile);
        req.setContent("尊敬的" + custName + ",您已开启数字证书服务,系统赠送的免费证书请在"+date
                + "前进行安装,如有疑问,请联系国付宝客服400-0550-009 ");
        ResponseVO resp = GopaySMSHttpClient.getInstance().createVerificationCode(req);

        if (resp != null) {
            if ("100".equals(resp.getStatusCode())) {
                logger.error("提醒企业客户安装免费数字证书短信已经发送成功！");
            } else {
                logger.error("提醒企业客户安装免费数字证书短信发送失败！，原因：" + resp.getMessage());
                throw new GopayException("提醒企业客户安装免费数字证书短信发送失败！，原因：" + resp.getMessage());
            }
        }
    }

    /**
     * @return the portalUrl
     */
    public String getPortalUrl() {
        return portalUrl;
    }

    /**
     * @param portalUrl the portalUrl to set
     */
    public void setPortalUrl(String portalUrl) {
        this.portalUrl = portalUrl;
    }

}
